package com.mediator
{
	import com.common.EventManager;
	import com.common.GlobalEvent;
	import com.common.Mediator;
	import com.view.EditClassView;
	import com.view.PropertyItem;
	import com.vo.AttributeVo;
	import com.vo.ClassVo;
	
	import flash.events.MouseEvent;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.managers.PopUpManager;

	public class EditClassMediator extends Mediator
	{
		public var view:EditClassView;

		public function EditClassMediator(view:EditClassView)
		{
			this.view = view;
			super(view);
		}

		public override function initListener():void{
			addEventListener(view.saveBtn, MouseEvent.CLICK, saveBtnHandler);
			
			addEventListener(view.addBtn, MouseEvent.CLICK, addBtnHandler);
			addEventListener(view.closeBtn, MouseEvent.CLICK, closeHandler);
			addEventListener(EventManager.instance, GlobalEvent.MINUSITEMEVENT, minusItemHandler);
		}

		private function closeHandler(e:MouseEvent):void{
			PopUpManager.removePopUp(view);
		}

		private var _vo:ClassVo;
		public function set vo(value:ClassVo):void{
			_vo = value;
			if(value){
				view.classNameLabel.text = value.className;
				var attrList:ArrayCollection = new ArrayCollection();
				for each(var item:AttributeVo in _vo.attributeList){
					attrList.addItem(item);
				}
				view.list = attrList;
			}else{
				view.classNameLabel.text = "";
				view.list = new ArrayCollection();
			}
		}

		public function get vo():ClassVo{
			return this._vo;
		}

		protected function addBtnHandler(event:MouseEvent):void
		{
			var item:AttributeVo = new AttributeVo();
			view.list.addItem(item);
		}

		private function minusItemHandler(evt:GlobalEvent):void
		{
			var item:AttributeVo = evt.obj as AttributeVo;
			view.list.removeItemAt(view.list.getItemIndex(item));
		}

		protected function saveBtnHandler(event:MouseEvent):void
		{
			var arr:Vector.<AttributeVo> = new Vector.<AttributeVo>();
			for(var i:int = 0; i <view.propertyList.dataGroup.numChildren ; i++)
			{
				var renderer:PropertyItem = view.propertyList.dataGroup.getChildAt(i) as PropertyItem;
				var item:AttributeVo = renderer.data as AttributeVo;
				
				if(item.attrName == "" || !item.attrName)
				{
					Alert.show("属性不能为空，清检查","提示");
					return;
				}
				if(item.attrType == "" || !item.attrType)
				{
					Alert.show("属性类型不能为空，清检查","提示");
					return;
				}
				arr.push(item);
			}
			if(_vo == null){
				_vo = new ClassVo();
				vo.attributeList = arr;
				vo.className = view.classNameLabel.text;
				EventManager.instance.dispatchEvent(new GlobalEvent(GlobalEvent.ADD_PROTO_CONFIG, vo));
			}else{
				vo.attributeList = arr;
				vo.className = view.classNameLabel.text;
				EventManager.instance.dispatchEvent(new GlobalEvent(GlobalEvent.SAVE_PROTO_CONFIG));
			}
		}
	}
}